﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.Collections.Specialized;
using BdcAdmin = Microsoft.SharePoint.BusinessData.Administration;
using Microsoft.Office.Server.Utilities;
using Microsoft.BusinessData;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.BusinessData.Administration;
using Microsoft.SharePoint.BusinessData.SharedService;
using Microsoft.SharePoint.BusinessData.MetadataModel;

namespace UpdateTemplateName
{
    class Program
    {
        // update the property in BDC model 
        // arguments
        // first  : SP Site
        // Second : Entity Name
        // Third  : Entity Name Space prperty
        // Fourth : Templatte Name
        static void Main(string[] args)
        {
            string spportalName = null;
            string entityNameproperty = null;
            string  entityNameSpaceproperty =null;
            string templateName = null;

            if (args.Length >= 4)
            {
                spportalName = args[0];
                entityNameproperty = args[1];
                entityNameSpaceproperty = args[2];
                templateName = args[3];
            }
            BdcAdmin.AdministrationMetadataCatalog catalog;

            SPSite spSite = new SPSite(spportalName);
            catalog = GetAdministrationMetadataCatalog(SPServiceContext.GetContext((spSite)));
            BdcAdmin.Entity entity = null;
            entity = catalog.GetEntity(entityNameSpaceproperty, entityNameproperty);

            foreach (BdcAdmin.Property property in entity.Properties)
            {
                if (property.Name == "WorkspaceSiteTemplate")
                {
                    property.Value = templateName;
                    break;
                }
            }           
        }

        internal static AdministrationMetadataCatalog GetAdministrationMetadataCatalog(SPServiceContext serviceContext)
        {

            AdministrationMetadataCatalog result = null;

            BdcService bdcService = SPFarm.Local.Services.GetValue<BdcService>(String.Empty);
            if (bdcService != null)
            {
                result = bdcService.GetAdministrationMetadataCatalog(serviceContext);
            }

            return result;

        }
    }
}
